import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import "./MovieAdd.css";

export default function MovieAdd() {
  const [title, setTitle] = useState("");
  const [duration, setDuration] = useState("");
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(null);
  const navigate = useNavigate();

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    setSuccess(null);

    // 简单验证
    if (!title.trim()) {
      setError("请输入电影标题");
      return;
    }

    if (!duration || isNaN(duration) || duration <= 0) {
      setError("请输入有效的电影时长");
      return;
    }

    try {
      const response = await fetch("http://localhost:8080/api/movies", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          title: title.trim(),
          duration: parseInt(duration, 10),
        }),
      });

      if (!response.ok) {
        throw new Error("添加电影失败");
      }

      const data = await response.json();
      setSuccess(`电影 "${data.title}" 添加成功！`);
      // 清空表单
      setTitle("");
      setDuration("");

      // 3秒后跳转到电影列表
      setTimeout(() => {
        navigate("/movies");
      }, 3000);
    } catch (error) {
      setError(error.message);
    }
  };

  return (
    <div className="movie-add-container">
      <h1>电影上架</h1>
      <div className="movie-form-container">
        <form className="movie-form" onSubmit={handleSubmit}>
          {error && <div className="error-message">{error}</div>}
          {success && <div className="success-message">{success}</div>}

          <div className="form-group">
            <label htmlFor="title">电影标题</label>
            <input
              type="text"
              id="title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="请输入电影标题"
            />
          </div>

          <div className="form-group">
            <label htmlFor="duration">电影时长 (分钟)</label>
            <input
              type="number"
              id="duration"
              value={duration}
              onChange={(e) => setDuration(e.target.value)}
              placeholder="请输入电影时长"
              min="1"
            />
          </div>

          <div className="form-actions">
            <button type="submit">提交</button>
            <button type="button" onClick={() => navigate("/movies")}>
              取消
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
